const api = require('../../../../ws_micro_shop/utils/api.js');
const utils = require('../../../../ws_micro_shop/utils/utils.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const app = getApp();

Page({
  data: {
    windowHeight: wx.systemInfo.windowHeight,
    position: true,
    empty: true,
    idx: 0,
    theme: app.themeData,
    show_payment: false,
    payment: -1,
    shownotice: false,
    date: '',
    unit: '',
    btnFreezen: false,
    imgUrl: app.imgUrl,
  },
  onLoad(opts) {
    let that = this;
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
    })
    let options = opts || {};
    let userinfo = wx.getStorageSync('user_info');
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    app.pageOnLoad(this);
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
    this.setData({
      opts: options,
    });
    this.getPreview(options);
  },
  checkboxChange(e) {
    let { pid, id } = e.currentTarget.dataset;
    let form_list = this.data.form_list;
    let is_selected = form_list[pid].default[id]['selected'];
    form_list[pid].default[id]['selected'] = !is_selected;
    this.setData({
      form_list,
    });
  },
  radioChange(e) {
    let { pid, id } = e.currentTarget.dataset;
    let form_list = this.data.form_list;
    for (let i in form_list[pid].default) {
      if (Object.prototype.hasOwnProperty.call(form_list[pid].default, i)) {
        form_list[pid].default[i]['selected'] = (Number(id) === Number(i));
      }
    }
    this.setData({
      form_list,
    });
  },
  dropdownlistChange(e) {
    let { id } = e.currentTarget.dataset;
    let form_list = this.data.form_list;
    let idx = e.detail.value;
    let pickerlist = form_list[id].default;
    for (let i in pickerlist) {
      if (Object.prototype.hasOwnProperty.call(pickerlist, i)) {
        pickerlist[i]['selected'] = false;
        pickerlist[idx]['selected'] = true;
        form_list[id].is_default = pickerlist[idx]['name'];
      }
    }
    this.setData({
      form_list,
    });
  },
  inputChenge(e) {
    let id = e.currentTarget.dataset.id;
    let form_list = this.data.form_list;
    form_list[id].default = e.detail.value;
    this.setData({
      form_list,
    });
  },
  pickTimeSet(e) {
    let idx = e.detail.value;
    let timeset = this.data.yy_list;
    this.setData({
      time_id: timeset[idx].id,
      idx,
    });
  },
  pickerdate(e) {
    let date = e.detail.value;
    let gid = this.data.goods.id;
    this.setData({
      date,
    });
    this.searchRepertory(gid, date);
  },
  searchRepertory(gid, date) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.book.count_search,
      method: 'GET',
      data: {
        gid,
        date,
      },
      success: function(res) {
        if (res.code === 0) {
          let timeset = res.data.yy_List;
          if (timeset && timeset.length > 0) {
            for (let k = 0; k < timeset.length; k++) {
              let item = timeset[k];
              item.timepoint = item.start + '-' + item.end + '剩余名额(' + item.limit + ')';
            }
          }
          that.setData({
            yy_list: timeset || [],
            time_id: timeset[0] && timeset[0].id || '',
          });
        }
      },
    });
  },
  getPreview(e) {
    let that = this;
    let gid = e.id;
    let payment = that.data.payment;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.book.submit_preview,
      method: 'GET',
      data: {
        gid,
        payment,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let { form_list, goods, userinfo, time, pay_type_list, card, card_discount, cancel, expire } = res.data;
          for (let i in form_list) {
            if (Object.prototype.hasOwnProperty.call(form_list, i)) {
              let item = form_list[i];
              if (item.type === 'date') {
                item.default = item.default || utils.formatData(new Date());
              }
              if (item.type === 'time') {
                item.default = item.default || '00:00';
              }
              if (item.type === 'dropdownlist') {
                for (let i in item.default) {
                  if (item.default[i].selected) {
                    item.is_default = item.default[i].name || '';
                    break;
                  }
                }
              }
              //判断类型是否为上传图片，如果是，将图片长度default赋值给imagesCount
              if (item.type === 'uploadimg') {
                item.imagesCount = item.default;
                //将item.default设为空数组，不然提交的时候，接口会冲突
                item.default = [];
              }
            }
          }
          that.searchRepertory(goods.id, time.start);
          that.setData({
            goods,
            userinfo,
            payment: that.data.payment,
            pay_type_list,
            card: card || '',
            card_discount: card_discount || '',
            form_list,
            dateset: time || '',
            date: time.start || '',
            cancel: cancel || '',
            expire: expire || '',
            empty: false,
          });
          wx.createSelectorQuery().select('.population').boundingClientRect(function (rect) {
            if (rect.height - 60 >= that.data.windowHeight) {
              that.setData({
                position: false,
              });
            }
          }).exec();
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.navigateBack();
              }
            },
          });
        }
      },
    });
  },
  submit(e) {
    let that = this;
    let form_id = e.detail.formId;
    let { goods, time_id, date, payment, form_list, btnFreezen } = that.data;

    if (btnFreezen) {
      return false;
    }
    app.getSubscribeMessage(4).then(response => {
    let gid = goods.id;
    let appoint_time = date;
    form_list = JSON.stringify(form_list);
    (!time_id) && (appoint_time = '');
    let formData = {
      gid,
      form_list,
      form_id,
      time_id,
      appoint_time,
      payment,
    };
    if (this.data.payment === -1 && goods.price > 0) {
      return wx.showToast({
        title: '请选择支付方式',
        icon: 'none',
      });
    }
    wx.showLoading({
      title: '正在提交',
      mask: true,
    });

    that.setData({
      btnFreezen: true,
    })
    app.ws_micro_shoprequest({
      url: api.book.submit,
      method: 'post',
      data: formData,
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          if (Number(res.type) === 1) {
            app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
              status: 1,
            }, true);
          } else {
            let order_id = res.order_id;
            if (Number(payment) === -1) {
              app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
                status: 1,
              }, true);
            }
            if (Number(payment) === 0) {
              app.ws_micro_shoprequest({
                url: api.book.order_pay,
                data: {
                  id: order_id,
                  pay_type: 'WECHAT_PAY',
                  form_id: e.detail.formId,
                },
                success: function (res) {
                  if (res.code === 0) {
                    let { timeStamp, nonceStr, signType, paySign } = res.data;
                    wx.requestPayment({
                      timeStamp,
                      nonceStr,
                      package: res.data.package,
                      signType,
                      paySign,
                      success: function () {
                        app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
                          status: 1,
                        }, true);
                      },
                      complete: function (e) {
                        if (e.errMsg === 'requestPayment:fail' || e.errMsg === 'requestPayment:fail cancel') {
                          wx.showModal({
                            title: '提示',
                            content: '订单尚未支付',
                            showCancel: false,
                            confirmText: '确认',
                            success: function (res) {
                              if (res.confirm) {
                                app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
                                  status: 0,
                                }, true);
                              }
                            },
                          });
                          return;
                        }
                        if (e.errMsg === 'requestPayment:ok') {
                          that.setData({
                            btnFreezen: false,
                          })
                          return;
                        }
                        app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
                          status: -1,
                        }, true);
                      },
                    });
                  } else {
                    wx.showToast({
                      title: res.msg || '',
                      icon: 'none',
                    });
                    setTimeout(function () {
                      app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', { status: 0 }, true);
                    }, 1000);
                    return;
                  }
                },
              });
            }
            if (Number(payment) === 2) {
              app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
                status: 1,
              }, true);
            }
            if (Number(payment) === 3) {
              app.ws_micro_shoprequest({
                url: api.book.order_pay,
                data: {
                  id: order_id,
                  pay_type: 'BALANCE_PAY',
                  form_id: e.detail.formId,
                },
                success: function (res) {
                  if (res.code === 0) {
                    app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
                      status: 1,
                    }, true);
                  } else {
                    wx.showToast({
                      title: res.msg || '',
                      icon: 'none',
                    });
                    setTimeout(function () {
                      app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', { status: 0 }, true);
                    }, 1000);
                    return;
                  }
                },
              });
            }
            if (Number(payment) === 5) {
              app.ws_micro_shoprequest({
                url: api.book.order_pay,
                data: {
                  id: order_id,
                  pay_type: 'CARD_PAY',
                  form_id: e.detail.formId,
                },
                success: function (res) {
                  if (res.code === 0) {
                    app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
                      status: 1,
                    }, true);
                  } else {
                    wx.showToast({
                      title: res.msg || '',
                      icon: 'none',
                    });
                    setTimeout(function () {
                      app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', { status: 0 }, true);
                    }, 1000);
                    return;
                  }
                },
              });
            }
          }
        } else {
          wx.hideLoading();
          that.setData({
            btnFreezen: false,
          })
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
          return;
        }
      },
      });
    });
  },
  showPayment() {
    this.setData({
      // show_payment: true,
    });
  },
  showNotice() {
    this.setData({
      shownotice: true,
    });
  },
  hideNotice() {
    this.setData({
      shownotice: false,
    });
  },
  payPicker(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      payment: index,
    });
  },
  payClose(e) {
    let that = this;
    let { pay_type_list } = that.data;
    let { index } = e.detail;
    let paytype = Number(pay_type_list[index].payment);
    if (paytype === 3) {
      wx.showModal({
        title: '友情提示',
        content: '是否确定选择账户余额支付',
        success: function (res) {
          if (res.confirm) {
            // that.getPreview(that.data.opts);
            that.setData({
              show_payment: false,
            });
          }
        },
      });
    } else if (paytype === 5) {
      let card = that.data.card;
      if (card) {
        // that.getPreview(that.data.opts);
        that.setData({
          show_payment: false,
        });
      } else {
        wx.showModal({
          title: '友情提示',
          content: '你还未开通会员卡，是否前往个人中心开通？',
          success: function (res) {
            if (res.confirm) {
              app.util.navigateTo('/ws_micro_shop/pages/user/user', {}, false);
            }
          },
        });
      }
    } else {
      // that.getPreview(that.data.opts);
      that.setData({
        show_payment: false,
      });
    }
    that.setData({
      payment: paytype,
    })
    // that.getPrice();
  },
  // 上传图片
  uploadEvent(e) {
    let form_list = this.data.form_list;
    let pid = Number(e.target.dataset.pid);  // 字符串作为数组索引,真机上会报错。
    let this_id = form_list[pid].id;
    form_list[pid].default = e.detail[this_id];
    this.setData({
      form_list,
    });
  },
});
